package com.cicadamob.contact.api.service;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.pinyin.PinyinTools;
import com.cicadamob.contact.api.service.AppDbHelper.COMPANY_COMMON_CONTACT;

public class CommonCompanyContactDao {

	public static final boolean insertCommonCompanyContact(Context context, String name,
			String phone, String uuid) {
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		boolean result = true;
		try {
			ContentValues values = new ContentValues();
			values.put(COMPANY_COMMON_CONTACT.DISPLAY_NAME, name);
			values.put(COMPANY_COMMON_CONTACT.PHONE, phone);
			values.put(COMPANY_COMMON_CONTACT.UUID, uuid);
			// long rowId = getContactIdByName(context, displayName);
			long rowId = db.insert(COMPANY_COMMON_CONTACT.TABLE_NAME, null, values);
			if (rowId != -1) {// 插入成功
				result = true;
				Intent intent = new Intent(APPContactDao.APP_CONTACT_CHNAGE);
				intent.putExtra(APPContactDao.APP_CONTACT_CHNAGE_TYPE,
						APPContactDao.APP_CONTACT_CHNAGE_TYPE_UPDATE_COMMON);
				intent.putExtra(APPContactDao.APP_CONTACT_CHNAGE_ID, (int) rowId);
				context.sendBroadcast(intent);
			} else {
				result = false;
			}
		} catch (Exception e) {
			// TODO 写日志
			result = false;
			e.printStackTrace();
		} finally {
			DBManager.getInstance(context).closeDatabase();
		}
		return result;
	}

	public static final List<Contact> getComanyCommonContact(Context context) {
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + COMPANY_COMMON_CONTACT.TABLE_NAME, null);

		List<Contact> contacts = new ArrayList<Contact>();
		Contact contact = new Contact();
		ArrayList<String> phones = new ArrayList<>();
		int lastId = -1;
		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor
					.getColumnIndex(COMPANY_COMMON_CONTACT.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor
					.getColumnIndex(COMPANY_COMMON_CONTACT.PHONE));
			int uuid = cursor.getInt(cursor.getColumnIndex(COMPANY_COMMON_CONTACT.UUID));
			int contactId = cursor.getInt(cursor.getColumnIndex(COMPANY_COMMON_CONTACT._ID));

			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			if (TextUtils.isEmpty(phoneNumber))
				continue;

			if (lastId != contactId) {
				if (lastId != -1) {
					contact.setPhoneList(phones);
					contacts.add(contact);
					contact = new Contact();
					phones = new ArrayList<>();
				}
				contact.setUserid("" + uuid);
				contact.setDisplayName(displayName);
				contact.setLinkPhone(phoneNumber);
				contact.setCommonContact(true);
				contact.setFromContact(true);
				if (StringUtil.isEmpty(displayName)) {
					contact.setLetter("#");
				} else {
					displayName = displayName.trim();
					String letter = PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
					char[] firstChar = letter.toCharArray();
					if (firstChar != null && firstChar.length > 0) {
						if (firstChar[0] >= 'a' && firstChar[0] <= 'z') {
							contact.setLetter(letter.toUpperCase());
						} else if (firstChar[0] >= 'A' && firstChar[0] <= 'Z') {
							contact.setLetter(letter);
						} else {
							contact.setLetter("#");
						}
					} else {
						contact.setLetter("#");
					}
				}
				contact.setFirstPy(PinyinTools.getFirstCharPinYin(displayName));
				contact.setAllPy(PinyinTools.getAllPinYin(displayName));
				contact.setSort(PinyinTools.getSort(displayName));
				// contact.setEmail(phoneEmail);
			}
			phones.add(phoneNumber);
			lastId = contactId;
		}
		if (lastId != -1) {
			contact.setPhoneList(phones);
			contacts.add(contact);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(context).closeDatabase();
		return contacts;
	}

	public static final boolean isCompanyCommonContact(Context context, String phone) {
		boolean isResult = false;
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		Cursor cursor = db.rawQuery("SELECT * FROM " + COMPANY_COMMON_CONTACT.TABLE_NAME
				+ " WHERE " + COMPANY_COMMON_CONTACT.PHONE + "=?", new String[] { phone });
		if (cursor.moveToNext()) {
			isResult = true;
		}
		DBManager.getInstance(context).closeDatabase();
		return isResult;

	}

	public static final boolean deleteCommonContact(Context context, String phone) {
		if (TextUtils.isEmpty(phone)) {
			return true;
		}
		boolean result = false;
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		try {
			db.delete(COMPANY_COMMON_CONTACT.TABLE_NAME, COMPANY_COMMON_CONTACT.PHONE + "=?",
					new String[] { phone });
			Intent intent = new Intent(APPContactDao.APP_CONTACT_CHNAGE);
			intent.putExtra(APPContactDao.APP_CONTACT_CHNAGE_TYPE,
					APPContactDao.APP_CONTACT_CHNAGE_TYPE_UPDATE_COMMON);
			intent.putExtra(APPContactDao.APP_CONTACT_CHNAGE_ID, 0);
			context.sendBroadcast(intent);
			result = true;
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		}
		DBManager.getInstance(context).closeDatabase();
		return result;
	}

	public static final boolean deleteCommonContact(Context context, int id) {
		if (id < 0) {
			return true;
		}
		boolean result = false;
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		try {
			db.delete(COMPANY_COMMON_CONTACT.TABLE_NAME, COMPANY_COMMON_CONTACT._ID + "=?",
					new String[] { id + "" });
			Intent intent = new Intent(APPContactDao.APP_CONTACT_CHNAGE);
			intent.putExtra(APPContactDao.APP_CONTACT_CHNAGE_TYPE,
					APPContactDao.APP_CONTACT_CHNAGE_TYPE_UPDATE_COMMON);
			intent.putExtra(APPContactDao.APP_CONTACT_CHNAGE_ID, id);
			context.sendBroadcast(intent);
			result = true;
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		}
		DBManager.getInstance(context).closeDatabase();
		return result;
	}

	public static final boolean deleteCommonContactByUUID(Context context, int uuid) {
		if (uuid < 0) {
			return true;
		}
		boolean result = false;
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		try {
			db.delete(COMPANY_COMMON_CONTACT.TABLE_NAME, COMPANY_COMMON_CONTACT.UUID + "=?",
					new String[] { uuid + "" });
			Intent intent = new Intent(APPContactDao.APP_CONTACT_CHNAGE);
			intent.putExtra(APPContactDao.APP_CONTACT_CHNAGE_TYPE,
					APPContactDao.APP_CONTACT_CHNAGE_TYPE_UPDATE_COMMON);
			intent.putExtra(APPContactDao.APP_CONTACT_CHNAGE_ID, 0);
			context.sendBroadcast(intent);
			result = true;
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		}
		DBManager.getInstance(context).closeDatabase();
		return result;
	}

}
